<?php
/**
 * initAddRoleForm()
 *
 * @return
 */
function initAddRoleForm()
{
    $form = new zeus_quickform(array("id" => "sv-form",
            "name" => "sv-form",
            "action" => "javascript:void(null)",
            "onsubmit" => "xajax_jsSubmitForm();",
            "method" => "post"));
    return $form;
}
/**
 * initEditRoleForm()
 *
 * @return
 */
function initEditRoleForm()
{
    $form = new zeus_quickform(array("id" => "sv-form",
            "onsubmit" => "xajax_jsSubmitForm();",
            "name" => "sv-form",
            "action" => "javascript:void(null)",
            "method" => "post"));
    return $form;
}
/**
 * initRoleFormElements()
 *
 * @return
 */
function initRoleFormElements($aRoleInfo = array())
{
    $role_name = (isset($aRoleInfo) && is_array($aRoleInfo))?"edit_role_name":"new_role_name";
    $elements = array(
        array("label" => array("for" => $role_name , "name" => _e("Role Name (required)")),
            "form" => array("type" => "text", "options" => array("id" => $role_name , "name" => $role_name , "value" => (isset($aRoleInfo))?$aRoleInfo['role_name']:$_POST['role_name']))),
        array("label" => array("for" => "description", "name" => _e("Description (required)")),
            "form" => array("type" => "text", "options" => array("id" => "description", "name" => "description", "value" => (isset($aRoleInfo))?$aRoleInfo['description']:$_POST['description'], "size" => 50, "maxlength" => 200)))
        );
    return $elements;
}

/**
 * showRoleFormCheck()
 *
 * @param mixed $oForm
 * @param array $aModule
 * @param mixed $aRoleInfo
 * @param mixed $bBind
 * @return
 */
function showRoleFormCheck($oForm, $aModule = array(), $aRoleInfo = null)
{
    $row[] = "<tr class='form-field'>" ;
    $row[] = "<th scope='row'>" ;
    // Bind data
    if (null != $aRoleInfo) {
        $check = (has_power($aModule['page_id'], $aRoleInfo['capability']))?true:false;
        $row[] = ($check)?
        ($oForm->addElement("checkbox", array("id" => "role-" . $aModule['page_id'], "name" => "check[]", "value" => $aModule['page_id'], "checked" => $check))):
        ($oForm->addElement("checkbox", array("id" => "role-" . $aModule['page_id'], "name" => "check[]", "value" => $aModule['page_id'])));
    }
    // or not
    else {
        $row[] = $oForm->addElement("checkbox", array("id" => "role-" . $aModule['page_id'], "name" => "check[]", "value" => $aModule['page_id']));
    }
    $row[] = $oForm->addElement("hidden", array("name" => "role[]", "value" => "role-" . $aModule['page_id']));
    $row[] = "<label for='" . $aModule['page_url'] . "'>" . $aModule['page_name'] . "</label></th>" ;
    $aSubMod = getOperate($aModule['page_id']);
    if (isset($aSubMod) && null != $aSubMod) {
        foreach($aSubMod AS $mod) {
            $aOperate = getOperate($mod['page_id']);
            $row[] = "<td>";
            // Bind data
            if (null != $aRoleInfo) {
                $check = (has_power($mod['page_id'], $aRoleInfo['capability']))?true:false;
                $row[] = ($check)?
                ($oForm->addElement("checkbox", array("id" => "role-" . $mod['page_id'], "name" => "check[]", "value" => $mod['page_id'], "checked" => $check))):
                ($oForm->addElement("checkbox", array("id" => "role-" . $mod['page_id'], "name" => "check[]", "value" => $mod['page_id'])));
            }
            // or not
            else {
                $row[] = $oForm->addElement("checkbox", array("id" => "role-" . $mod['page_id'], "name" => "check[]", "value" => $mod['page_id']));
            }
            $row[] = $oForm->addElement("hidden", array("name" => "role[]", "value" => "role-" . $mod['page_id']));
            $row[] = _e($mod['page_name']) . "<br>";
            if (isset($aOperate) && null != $aOperate) {
                foreach($aOperate AS $operate) {
                    // Bind data
                    if (null != $aRoleInfo) {
                        $check = (has_power($operate['page_id'], $aRoleInfo['capability']))?true:false;
                        $row[] = ($check)?($oForm->addElement("checkbox", array("id" => "role-" . $operate['page_id'], "name" => "check[]", "value" => $operate['page_id'], "checked" => $check))
                             . _e($operate['page_name'])
                             . "<br>"):
                        ($oForm->addElement("checkbox", array("id" => "role-" . $operate['page_id'], "name" => "check[]", "value" => $operate['page_id']))
                             . _e($operate['page_name'])
                             . "<br>");
                    }
                    // or not
                    else {
                        $row[] = $oForm->addElement("checkbox", array("id" => "role-" . $operate['page_id'], "name" => "check[]", "value" => $operate['page_id']))
                         . _e($operate['page_name'])
                         . "<br>";
                    }
                    $row[] = $oForm->addElement("hidden", array("name" => "role[]", "value" => "role-" . $operate['page_id']));
                }
            }
            $row[] = "</td>";
        }
    }
    $row[] = "</tr>";
    return implode("\n\t", $row);
}

/**
 * getOperate()
 *
 * @param string $sModuleId
 * @return
 */
function getOperate($sModuleId = "")
{
    if (isset($sModuleId) && "" != $sModuleId) {
        $sql = "SELECT page_id,page_name,page_url FROM " . DB_PREFIX . "modules WHERE parent_id='" . $sModuleId . "' AND page_id!='0'";
        $result = zeus_sql_query($sql, false, 'All');
        if (isset($result)) {
            return $result;
        } else {
            return false;
        }
    }
}
/**
 * showRoleGridRow()
 *
 * @param array $aRole
 * @param string $sStyle
 * @param mixed $bDelete
 * @return
 */
function showRoleGridRow($oGrid, $aRole = array(), $sStyle = "")
{
    $row[] = "<tr id='role-" . $aRole['role_id'] . $sStyle . ">";
    if ($oGrid->bDelete) {
        $row[] = "<th scope='row' class='check-column'>"
         . $oGrid->oForm->addElement("checkbox", array("name" => "check[]", "id" => "row-" . $aRole['role_id'], "value" => $aRole['role_id']))
         . $oGrid->oForm->addElement("hidden", array("name" => "row[]", "value" => "row-" . $aRole['role_id']))
         . "</th>";
    } else {
        $row[] = "";
    }
    if ($oGrid->bEdit) {
        $edit = "?action=edit_role&role_id=" . $aRole['role_id'];
    } elseif ($oGrid->bView) {
        $edit = "?action=view_role&role_id=" . $aRole['role_id'];
    } else {
        $edit = "#";
    }
    $row[] = "<td><strong><a href='" . $_SERVER['PHP_SELF'] . $edit . "'>" . $aRole['role_name'] . "</a></strong></td>";
    $row[] = "<td> " . $aRole['description'] . "</td>";
    $row[] = "<td class = 'num'> " . $aRole['member_num'] . "</td>";
    $row[] = "</tr>";
    return implode("\n\t", $row);
}
/**
 * initRoleGrid()
 *
 * @return
 */
function initRoleGrid()
{
    //Create heap
    createRoleGridHeap();
    //Init grid
	$grid = new zeus_datagrid();
    $grid->oForm = new zeus_quickform(array("id" => "posts-filter", "method" => "get"));
    if (is_object($grid)) {
        // Set grid title
        $grid->sGridTitle = _e("Manage Roles");
        // Set id column
        $grid->sIdColumn = DB_PREFIX . "role_grid_view . role_id";
        // Set operate
        $grid->bEdit = can_operate('edit_role', $_SESSION['user_id']);
        $grid->bAdd = can_operate('add_role', $_SESSION['user_id']);
        $grid->bView = can_operate('view_role', $_SESSION['user_id']);
        $grid->bDelete = can_operate('del_role', $_SESSION['user_id']);
        $grid->bDebug = false;
        // Set submenu
        $grid->aSubMenu = null;
        // Set table
        $grid->sTable = array(DB_PREFIX . 'role_grid_view');
        // Set column display name
        $grid->aColumn = array("checkbox" => array("name" => $grid->oForm->addElement("checkbox", array("name" => "checkAllRole", "id" => "checkAllRole", "onclick" => "xajax_checkAllRole(this.checked);return false;"))),
            "role_name" => array("name" => _e("Role Name"), "field" => "role_name"),
            "description" => array("name" => _e("Description"), "field" => "description"),
            "comments" => array("name" => _e("Member Number"), "field" => "member_num")
            );
        if (!$grid->bDelete) {
            $grid->aColumn = array_slice($grid->aColumn, 1);
        } else {
            zeus_do_nothing();
        }
        // Set fields
        $grid->aField = array(
            DB_PREFIX . "role_grid_view . role_id",
            DB_PREFIX . "role_grid_view . role_name",
            DB_PREFIX . "role_grid_view . description",
            DB_PREFIX . "role_grid_view . member_num"
            );
        // Set select
        $grid->aSelect = null;
        // Set match
        $grid->sMatch = null;
        // Set whole only
        $grid->bWholeOnly = false;
        // Set order
        $grid->sOrder = isset($_GET['order'])?$_GET['order']:null;
        // Sett order type
        $grid->sOrderType = isset($_GET['type'])?$_GET['type']:null;
        // Set status
        if (isset($_GET['status']) && null != $_GET['status']) {
            switch ($_GET['status']) {
                case "1":
                case "0":
                    $grid->bWholeOnly = true;
                    $grid->sFilter = $_GET['status'];
                    $grid->sFilterField = DB_PREFIX . "user_auth . is_enable";
                    break;
                default:
                    $grid->sFilterField = null;
                    $grid->sFilter = null;
                    break;
            }
        }
        // Set search
        elseif (isset($_GET['submit']) && (_e('Search')) == $_GET['submit']) {
            $grid->sFilter = $_GET['search'];
        }
        // Set filtrate field
        elseif (isset($_GET['filtrate']) && _e('Filtrate') == $_GET['filtrate']) {
            if (isset($_GET['filtrate_role']) && null != $_GET['filtrate_role']) {
                switch ($_GET['filtrate_role']) {
                    case "-1":
                        $grid->sFilterField = null;
                        $grid->sFilter = null;
                        break;
                    case "1":
                    case "2":
                    case "3":
                    case "4":
                    case "5":
                    case "6":
                    case "7":
                    case "8":
                        $grid->sFilter = $_GET['filtrate_role'];
                        $grid->sFilterField = DB_PREFIX . "user_auth . role_id";
                        break;
                    default:
                        $grid->sFilterField = null;
                        $grid->sFilter = null;
                        break;
                }
            } else {
                $grid->sFilterField = null;
                $grid->sFilter = null;
            }
        } else {
            $grid->sFilterField = null;
            $grid->sFilter = null;
        }
    } else {
        zeus_do_nothing();
    }
    return $grid;
}
/**
 * getRoleNumber()
 *
 * @param string $sRoleId
 * @return
 */
function getRoleNumber($sRoleId = "")
{
    if (isset($sRoleId) && "" != $sRoleId) {
        $sql = "SELECT COUNT(DISTINCT user_id) FROM " . DB_PREFIX . "user_auth WHERE role_id = '" . $sRoleId . "'";
        $result = zeus_sql_query($sql, false);
        $key = "COUNT(DISTINCT user_id)";
        $result = (isset($result))? $result[$key]:0;
    } else {
        $result = 0;
    }
    return $result;
}
/**
 * getRoleInfo()
 *
 * @param string $sRoleId
 * @return
 */
function getRoleInfo($sRoleId = "")
{
    if (isset($sRoleId) && "" != $sRoleId) {
        $sql = "SELECT * FROM " . DB_PREFIX . "role WHERE role_id='" . $sRoleId . "'";
        $result = zeus_sql_query($sql, false);
        if (isset($result) && null != $result) {
            return $result;
        } else {
            return false;
        }
    } else {
        return false;
    }
}
/**
 * has_power()
 *
 * @param string $sPower
 * @param string $sAllPower
 * @return
 */
function has_power($sPower = "", $sAllPower = "")
{
    $aAllPower = explode(",", $sAllPower);
    return in_array($sPower, $aAllPower);
}
/**
 * editRoleInfo()
 *
 * @param string $sRoleId
 * @return
 */
function editRoleInfo($sRoleId = "", $aForm = array())
{
    $role_id = $sRoleId;
    $role_name = $aForm['edit_role_name'];
    $descrption = $aForm['description'];
    $dashboard = array("0", "6", "23"); //Dashbord,User,Profile is default modules.
    if (isset($aForm['check']) && is_array($aForm['check'])) {
        $privielge = array_unique(array_merge($dashboard, $aForm['check']));
        sort($privielge, SORT_NUMERIC);
        $capability = implode(",", $privielge);
    } else {
        $capability = implode(",", $dashboard);
    }
    $sql = "UPDATE " . DB_PREFIX . "role SET
role_name = '" . $role_name . "',description='" . $descrption . "',capability='" . $capability . "' WHERE role_id='" . $role_id . "'";
    if (zeus_sql_exec($sql, false)) {
        return true;
    } else {
        return false;
    }
}
/**
 * updateTheRoleAllUser()
 *
 * @param string $sRoleId
 * @return
 */
function updateTheRoleAllUser($sRoleId = "")
{
    // Get role capability
    $sql = "SELECT capability FROM " . DB_PREFIX . "role WHERE role_id='" . $sRoleId . "'";
    $result = zeus_sql_query($sql, false);
    if (isset($result)) {
        $capability = $result['capability'];
    } else {
        $capability = false;
    }
    // Get user id
    $sql = "SELECT user_id FROM " . DB_PREFIX . "user_auth WHERE role_id='" . $sRoleId . "'";
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result)) {
        foreach($result AS $user) {
            $aUsers[] = array(":user_id" => $user['user_id'],
                ":privilege" => $capability);
        }
    } else {
        $aUsers = false;
    }
    // Update the users' capability
    if (true == $capability && is_array($aUsers)) {
        $sql = "UPDATE " . DB_PREFIX . "privilege SET privilege=:privilege
		WHERE user_id=:user_id";
        zeus_sql_prepare($sql, false, $aUsers);
    } else {
        return false;
    }
}
/**
 * getAllRole()
 *
 * @return
 */
function getAllRole()
{
    $sql = "SELECT role_id,role_name FROM " . DB_PREFIX . "role";
    $result = zeus_sql_query($sql, false, 'All');
    if (isset($result)) {
        foreach($result AS $role) {
            $key[] = $role['role_id'];
            $value[] = $role['role_name'];
        }
        $roleInfo = array_combine($key, $value);
        return $roleInfo;
    } else {
        return false;
    }
}

?>